require('dotenv').config();
const { sequelize, connectDB } = require('../config/database');
const { User, Category, Product, Cart, Order, OrderItem } = require('../models');

const seedData = async () => {
    try {
        await connectDB();
        
        // 手动按正确顺序删除表（避免外键约束问题）
        // 修改前的表删除顺序
        // await sequelize.getQueryInterface().dropTable('order_items');
        // await sequelize.getQueryInterface().dropTable('orders');
        // await sequelize.getQueryInterface().dropTable('carts');
        // await sequelize.getQueryInterface().dropTable('products');
        // await sequelize.getQueryInterface().dropTable('categories');
        // await sequelize.getQueryInterface().dropTable('users');
        
        // 修改后的表删除顺序 - 按正确的外键依赖关系删除
await sequelize.getQueryInterface().dropTable('order_items');
await sequelize.getQueryInterface().dropTable('orders');
await sequelize.getQueryInterface().dropTable('cart_items');
await sequelize.getQueryInterface().dropTable('carts');
await sequelize.getQueryInterface().dropTable('addresses'); // 新增的删除操作
await sequelize.getQueryInterface().dropTable('products');
await sequelize.getQueryInterface().dropTable('categories');
await sequelize.getQueryInterface().dropTable('users');
        
        // 重新创建表
        await sequelize.sync();
        console.log('数据库已重置');

        // 创建管理员用户
        const admin = await User.create({
            username: 'admin',
            email: 'admin@eshop.com',
            password: 'Admin123!',
            firstName: '管理员',
            lastName: '系统',
            role: 'admin'
        });
        
        // 创建测试用户
        const customer = await User.create({
            username: 'customer',
            email: 'customer@example.com',
            password: 'Customer123!',
            firstName: '测试',
            lastName: '用户',
            role: 'customer'
        });

        // 创建商品分类
        const categories = await Category.bulkCreate([
            {
                name: '电子产品',
                description: '手机、电脑、数码产品等',
                sortOrder: 1
            },
            {
                name: '服装鞋帽',
                description: '男装、女装、鞋类、配饰等',
                sortOrder: 2
            },
            {
                name: '家居生活',
                description: '家具、家电、日用品等',
                sortOrder: 3
            },
            {
                name: '图书音像',
                description: '书籍、音乐、影视等',
                sortOrder: 4
            }
        ]);

        // 创建测试商品
        const products = [];
        for (let i = 1; i <= 50; i++) {
            products.push({
                name: `测试商品 ${i}`,
                description: `这是测试商品 ${i} 的详细描述，包含了商品的特点和优势。`,
                shortDescription: `测试商品 ${i} 的简短描述`,
                sku: `SKU${i.toString().padStart(3, '0')}`,
                price: (Math.random() * 1000 + 10).toFixed(2),
                originalPrice: (Math.random() * 1200 + 50).toFixed(2),
                stock: Math.floor(Math.random() * 100) + 10,
                categoryId: categories[Math.floor(Math.random() * categories.length)].id,
                isActive: true,
                isFeatured: Math.random() > 0.7
            });
        }
        
        await Product.bulkCreate(products);

        console.log('✅ 种子数据创建完成');
        console.log('📧 管理员账户: admin@eshop.com / Admin123!');
        console.log('📧 测试账户: customer@example.com / Customer123!');
        
        process.exit(0);
    } catch (error) {
        console.error('❌ 种子数据创建失败:', error);
        process.exit(1);
    }
};

seedData();